#!/bin/bash

# Function to get the port location of rtl88x2bu device
check_port() {
    local output=$(lsusb -t)
    if echo "$output" | grep -q "rtl88x2bu, 5000M"; then
        local port=$(echo "$output" | grep "rtl88x2bu, 5000M" | sed -E 's/.*Port ([0-9]+):.*/\1/')
        if [ "$port" = "1" ]; then
            echo "Top"
        elif [ "$port" = "2" ]; then
            echo "Bottom"
        else
            echo "Error"
        fi
    else
        echo "Error"
    fi
}

# Function to get the current path setting
check_path() {
    local current_path=$(uci get wireless.radio1.path)
    local bottom_path="scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb2/2-2/2-2:1.0"
    local top_path="scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb2/2-1/2-1:1.0"

    if [ "$current_path" == "$bottom_path" ]; then
        echo "Bottom"
    elif [ "$current_path" == "$top_path" ]; then
        echo "Top"
    else
        echo "Error"
    fi
}

# Main execution
path_location=$(check_path)
port_location=$(check_port)

# Compare and adjust if necessary
if [ "$path_location" != "$port_location" ]; then
    if [ "$path_location" = "Top" ] && [ "$port_location" = "Bottom" ]; then
        uci set wireless.radio1.path="scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb2/2-2/2-2:1.0"
        uci commit wireless
sh /etc/sysp/reboot.sh
				echo "Path updated to Bottom"
    elif [ "$path_location" = "Bottom" ] && [ "$port_location" = "Top" ]; then
        uci set wireless.radio1.path="scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb2/2-1/2-1:1.0"
        uci commit wireless
sh /etc/sysp/reboot.sh
			  echo "Path updated to Top"
				
    else
        echo "Error in determining correct action."
        exit 1
    fi
elif [ "$path_location" = "Error" ] || [ "$port_location" = "Error" ]; then
    echo "Error occurred in either path or port check."
    exit 1
else
    echo "Path and port match. No action needed."
fi